﻿using System;
using System.Globalization;
using System.IO;
using System.Net;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace Simple.Tfs{
    public class AttachmentController{
        private readonly WorkItemStore _workItemStore;
        public bool DirectoryPerWorkItem { get; set; }

        public string DownloadFolder { get; set; }

        public AttachmentController(TfsTeamProjectCollection collection){
            collection.Authenticate();
            _workItemStore = new WorkItemStore(collection);
        }

        public void Download(WorkItemCollection collection){
            if (!Directory.Exists(DownloadFolder)){
                Directory.CreateDirectory(DownloadFolder);
            }
            foreach (WorkItem item in collection){
                if (item == null){
                    continue;
                }
                WebClient request = new WebClient{Credentials = CredentialCache.DefaultCredentials};

                foreach (Attachment attachment in item.Attachments){
                    string itemDownloadDirectory = DownloadFolder;
                    if (DirectoryPerWorkItem){
                        itemDownloadDirectory = Path.Combine(DownloadFolder, item.Id.ToString(CultureInfo.InvariantCulture));
                        Directory.CreateDirectory(itemDownloadDirectory);
                    }
                    OnDownloadStarted(new FileDownloadEventArgs{FileName = attachment.Name});
                    request.DownloadFile(attachment.Uri, Path.Combine(itemDownloadDirectory, attachment.Name));
                    OnDownloadCompleted(new FileDownloadEventArgs{FileName = attachment.Name});
                }
            }
        }

        public WorkItemCollection GetWorkItems(){
            return GetWorkItems("SELECT [System.Id] FROM workitems where [System.AttachedFileCount]>0");
        }

        public WorkItemCollection GetWorkItems(string statement){
            Query query = new Query(_workItemStore, statement);
            return query.RunQuery();
        }

        protected virtual void OnDownloadCompleted(FileDownloadEventArgs e){
            EventHandler<FileDownloadEventArgs> handler = DownloadCompleted;
            if (handler != null){
                handler(this, e);
            }
        }

        protected virtual void OnDownloadStarted(FileDownloadEventArgs e){
            EventHandler<FileDownloadEventArgs> handler = DownloadStarted;
            if (handler != null){
                handler(this, e);
            }
        }

        public event EventHandler<FileDownloadEventArgs> DownloadStarted;
        public event EventHandler<FileDownloadEventArgs> DownloadCompleted;
    }
}